package cn.edu.sasu.service.impl;

import cn.edu.sasu.common.base.LayuiRespResult;
import cn.edu.sasu.common.base.RespResult;
import cn.edu.sasu.common.constants.Constant;
import cn.edu.sasu.common.exception.BusinessException;
import cn.edu.sasu.common.util.CookieUtil;
import cn.edu.sasu.common.util.DateUtils;
import cn.edu.sasu.common.util.SessionUtil;
import cn.edu.sasu.domain.dto.SysUserSaveDTO;
import cn.edu.sasu.domain.dto.UpdatePasswordDTO;
import cn.edu.sasu.domain.entity.SysUser;
import cn.edu.sasu.domain.vo.SysUserInfoVO;
import cn.edu.sasu.domain.vo.SysUserVO;
import cn.edu.sasu.mapper.SysUserMapper;
import cn.edu.sasu.mapper.SysUserRoleMapper;
import cn.edu.sasu.service.SysUserService;
import cn.hutool.core.bean.BeanUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;

//用户业务逻辑处理
@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysUserRoleMapper userRoleMapper;

    @Override
    public RespResult login(HttpServletResponse response, String username, String password) {
        // 1. 根据用户名查询系统用户信息
        SysUser sysUser = sysUserMapper.findSysUserByUsername(username);
        // 2. 用户名存在
        if(sysUser != null && sysUser.getPassword().equals(password)){
            // 对象拷贝SysUser = SysUserInfoVO
            SysUserInfoVO sysUserInfoVO = BeanUtil.copyProperties(sysUser, SysUserInfoVO.class);
            SysUser currentUser = BeanUtil.copyProperties(sysUserInfoVO, SysUser.class);
            /*获取登录用户对应的角色*/
            int roleByUserId = userRoleMapper.getRoleByUserId(sysUser.getUserId());
            /*获取cookie*/
            String cookie = CookieUtil.generateCookieByUserId(sysUser.getUserId(), roleByUserId);
            CookieUtil.setCookieValueIntoResponse(response,cookie);
            /*将用户id为键，对应的cookie作为值*/
            SessionUtil.putSession(sysUser.getUserId(),cookie);

            return RespResult.success("登录成功",sysUserInfoVO);
        }else{
            return RespResult.error("用户名或密码有误！");
        }
    }

    @Override
    public RespResult updatePassword(UpdatePasswordDTO updatePasswordDTO) {
        // 1. 把客户端传递的老密码与登录账户密码进行校验
        SysUser sysUser = sysUserMapper.findSysUserByUserId(updatePasswordDTO.getUserId());
        if(sysUser != null){
            if(!sysUser.getPassword().equals(updatePasswordDTO.getOldPassword())){
                return RespResult.error("当前密码不正确！");
            }
            // 2. 修改当前用户密码
            sysUserMapper.updatePassword(updatePasswordDTO.getUserId(),updatePasswordDTO.getNewPassword());
        }
        return RespResult.success("修改密码成功！");
    }

    @Override
    public LayuiRespResult findSysUserAll(Integer page,Integer limit) {
        Integer offset = (page - 1) * limit;
        Integer rows = limit;
        List<SysUserVO> sysUsers = sysUserMapper.findSysUserList(Constant.DELETE_FLAG_YES,offset,rows);
        Integer totalSize = sysUserMapper.countSysUser(Constant.DELETE_FLAG_YES);
        return LayuiRespResult.success(totalSize,sysUsers);
    }

    @Override
    public RespResult delSysUserByUserId(Integer userId) {
        sysUserMapper.updateSysUserDeleteFlagByUserId(userId,Constant.DELETE_FLAG_YES);
        return RespResult.success("删除成功！");
    }

    @Override
    public RespResult batchdel(Integer[] userIds) {
        sysUserMapper.updateSysUserDeleteFlagByUserIds(Arrays.asList(userIds),Constant.DELETE_FLAG_YES);
        return RespResult.success("删除成功！");
    }

    @Override
    public LayuiRespResult search(Integer page, Integer limit, String username) {
        Integer offset = (page - 1) * limit;
        Integer rows = limit;
        List<SysUserVO> sysUsers = sysUserMapper.searchSysUserList(Constant.DELETE_FLAG_YES,offset,rows,username);
        Integer totalSize = sysUserMapper.countSearchSysUser(Constant.DELETE_FLAG_YES,username);
        return LayuiRespResult.success(totalSize,sysUsers);
    }

    @Override
    public RespResult save(SysUserSaveDTO sysUserSaveDTO) {
        SysUser user = sysUserMapper.findSysUserByUsername(sysUserSaveDTO.getUsername());
        if(user != null){
             return RespResult.error("该用户名已经存在，请重新输入！");
        }
        // 对象拷贝
        SysUser sysUser = BeanUtil.copyProperties(sysUserSaveDTO,SysUser.class);
        sysUser.setCreateDate(DateUtils.getCurrentDate());
        sysUserMapper.save(sysUser);
        return RespResult.success("添加成功");
    }

    @Override
    public RespResult updateInfo(SysUserInfoVO sysUserInfoVO) {
        sysUserInfoVO.setUpdateDate(DateUtils.getCurrentDate());
        Integer integer = sysUserMapper.updateInfo(sysUserInfoVO);
        if (integer > 0) {
            return RespResult.success("修改成功", sysUserMapper.findSysUserByUserId(sysUserInfoVO.getUserId()));
        } else {
            return RespResult.error("修改失败");
        }
    }
}
